<template>
  <!-- 临时授权页面 -->
  <div class="door">
    <!-- 时间批量修改 -->
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="120px">
      <el-form-item label>
        <el-checkbox v-model="AdminChecked">系统内人员</el-checkbox>
      </el-form-item>
      <!-- 非系统内人员数据 -->
      <el-form-item label="卡号" v-show="!AdminChecked" prop="cardNumber">
        <el-input placeholder="请输入卡号" v-model="ruleForm.cardNumber" style="width:250px" clearable  size="mini"></el-input>
      </el-form-item>
      <el-form-item label="姓名" v-show="!AdminChecked" prop="userName">
        <el-input placeholder="请选择输入姓名" v-model="ruleForm.userName" style="width:250px" clearable  size="mini"></el-input>
      </el-form-item>
      <el-form-item label="出生日期" v-show="!AdminChecked" prop="birthday">
        <el-date-picker v-model="ruleForm.birthday" type="date" placeholder="选择日期"  size="mini"></el-date-picker>
      </el-form-item>
      <el-form-item label="性别" v-show="!AdminChecked" prop="sex">
        <el-radio v-model="ruleForm.sex" label="0">男</el-radio>
        <el-radio v-model="ruleForm.sex" label="1">女</el-radio>
      </el-form-item>
      <el-form-item label="联系电话" v-show="!AdminChecked" prop="phone">
        <el-input placeholder="请选择输入联系电话" v-model="ruleForm.phone" style="width:250px" clearable  size="mini"></el-input>
      </el-form-item>
      <el-form-item label="身份证" v-show="!AdminChecked" prop="idCard">
        <el-input placeholder="请选择输入身份证" v-model="ruleForm.idCard" style="width:250px" clearable  size="mini"></el-input>
      </el-form-item>
      <el-form-item label="现居住地址" v-show="!AdminChecked" prop="position">
        <el-input placeholder="请选择输入现居住地址" v-model="ruleForm.position" style="width:400px"  size="mini"></el-input>
      </el-form-item>
      <!-- 系统内人员数据 -->
      <el-form-item label="人员姓名" v-show="AdminChecked">
        <el-input
          placeholder="请选择人员"
          v-model="userName"
          style="width:250px"
          clearable
          :disabled="true"
          size="mini"
        ></el-input>
        <el-button type="primary" @click="createPersonnel" size="mini">添加人员</el-button>
      </el-form-item>
      <el-form-item label="房间号">
        <el-input
          placeholder="请选择房间"
          v-model="roomName"
          style="width:250px"
          clearable
          :disabled="true"
          size="mini"
        ></el-input>
        <el-button type="primary" @click="createRoom" size="mini">添加房间</el-button>
      </el-form-item>
      <el-form-item label="有效时间">
        <el-date-picker
          v-model="startTime"
          type="datetime"
          placeholder="选择日期时间"
          value-format="yyyy-MM-dd HH:mm:ss"
          :default-time="'00:00:00'"
          size="mini"
          style="width:180px"
        ></el-date-picker>
        <span class="time">至</span>
        <el-date-picker
          v-model="endTime"
          type="datetime"
          placeholder="选择日期时间"
          value-format="yyyy-MM-dd HH:mm:ss"
          :default-time="'23:59:59'"
          size="mini"
          style="width:180px"
        ></el-date-picker>
        <el-button type="primary" @click="oneDay(1)" size="mini">一天</el-button>
        <el-button type="primary" @click="oneDay(7)" size="mini">一周</el-button>
        <el-button type="primary" @click="oneDay(30)" size="mini">一月</el-button>
        <el-button type="primary" @click="oneDay(365)" size="mini">一年</el-button>
        <el-button type="primary" @click="resetTime()" size="mini">置为当前时间</el-button>
      </el-form-item>
      <!-- <el-form-item label="延长有效期"></el-form-item> -->
      <el-form-item label="密码">
        <el-input placeholder="请输入密码" v-model="password" style="width:250px" clearable size="mini"></el-input>
        <el-checkbox v-model="backLock">反锁开门</el-checkbox>
      </el-form-item>
      <el-form-item label="假日时段">
        <el-select
          v-model="valHoliday"
          placeholder="请选择"
          size="mini"
          @change="handleValOne(valHoliday,'holidayTimeStageIndex')"
        >
          <el-option v-for="item in 16" :key="item - 1" :label="item - 1" :value="item - 1"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="是否可开">
        <el-checkbox v-model="mondayChecked">星期一</el-checkbox>
        <el-checkbox v-model="tuesdayChecked" class="checked">星期二</el-checkbox>
        <el-checkbox v-model="wednesdayChecked" class="checked">星期三</el-checkbox>
        <el-checkbox v-model="thursdayChecked" class="checked">星期四</el-checkbox>
        <el-checkbox v-model="fridayChecked" class="checked">星期五</el-checkbox>
        <el-checkbox v-model="saturdayChecked" class="checked">星期六</el-checkbox>
        <el-checkbox v-model="sundayChecked" class="checked">星期日</el-checkbox>
      </el-form-item>
      <el-form-item label="星期时段">
        <el-select
          v-model="valMonday"
          placeholder="请选择"
          size="mini"
          style="width:82px; "
          @change="handleValOne(valMonday,'mondayTimeStageIndex')"
          :disabled="!mondayChecked"
        >
          <el-option v-for="item in 16" :key="item - 1" :label="item - 1" :value="item - 1"></el-option>
        </el-select>
        <!-- // tuesdayChecked,wednesdayChecked,thursdayChecked,fridayChecked,saturdayChecked,sundayChecked -->

        <el-select
          v-model="valTuesday"
          placeholder="请选择"
          size="mini"
          style="width:82px;margin-left:15px "
          @change="handleValOne(valTuesday,'tuesdayTimeStageIndex')"
          :disabled="!tuesdayChecked"
        >
          <el-option v-for="item in 16" :key="item - 1" :label="item - 1" :value="item - 1"></el-option>
        </el-select>
        <el-select
          v-model="valWednesday"
          placeholder="请选择"
          size="mini"
          style="width:82px;margin-left:15px "
          @change="handleValOne(valWednesday,'wednesdayTimeStageIndex')"
          :disabled="!wednesdayChecked"
        >
          <el-option v-for="item in 16" :key="item - 1" :label="item - 1" :value="item - 1"></el-option>
        </el-select>
        <el-select
          v-model="valThursday"
          placeholder="请选择"
          size="mini"
          style="width:82px;margin-left:15px "
          @change="handleValOne(valThursday,'thursdayTimeStageIndex')"
          :disabled="!thursdayChecked"
        >
          <el-option v-for="item in 16" :key="item - 1" :label="item - 1" :value="item - 1"></el-option>
        </el-select>
        <el-select
          v-model="valFriday"
          placeholder="请选择"
          size="mini"
          style="width:82px;margin-left:15px "
          @change="handleValOne(valFriday,'fridayTimeStageIndex')"
          :disabled="!fridayChecked"
        >
          <el-option v-for="item in 16" :key="item - 1" :label="item - 1" :value="item - 1"></el-option>
        </el-select>
        <el-select
          v-model="valSaturday"
          placeholder="请选择"
          size="mini"
          style="width:82px; margin-left:15px"
          @change="handleValOne(valSaturday,'saturdayTimeStageIndex')"
          :disabled="!saturdayChecked"
        >
          <el-option v-for="item in 16" :key="item - 1" :label="item - 1" :value="item - 1"></el-option>
        </el-select>
        <el-select
          v-model="valSunday"
          placeholder="请选择"
          size="mini"
          style="width:82px; margin-left:15px"
          @change="handleValOne(valSunday,'sundayTimeStageIndex')"
          :disabled="!sundayChecked"
        >
          <el-option v-for="item in 16" :key="item - 1" :label="item - 1" :value="item - 1"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">提交</el-button>
      </el-form-item>
    </el-form>
    <!-- 房间人员设定弹窗 -->
    <add-room-jon
      v-if="addroomjonVisible"
      ref="addroomjoin"
      @refreshDataList="refreshDataList"
      :isPersonnel="true"
    ></add-room-jon>
    <!-- 楼层设定弹窗 -->
    <add-build-room
      v-if="addbuildroomVisible"
      ref="addbuildroomjoin"
      @refbuildDataList="refbuildDataList"
    ></add-build-room>
  </div>
</template>
<script>
import bus from '@/bus.js'
import AddRoomJon from './door-lock-personnel-add-join'
import AddBuildRoom from './regional-building-room'
export default {
  data() {
    return {
      operatorGuid: '',
      ruleForm: {
        cardNumber: '',
        userName: '',
        phone: '',
        idCard: '',
        position: '',
        sex: '0',
        birthday: ''
      },
      rules: {
        cardNumber: [
          { required: true, message: '请输入卡号', trigger: 'blur' }
        ],
        userName: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
        birthday: [
          { required: true, message: '请选择出生年月', trigger: 'blur' }
        ]
      },
      loading: false,
      detailslist: [],
      pageNum: 1,
      pageSize: 10,
      currentPage: 1,
      recordCount: 0,
      searchInfo: {},

      radio: '男',
      // 系统内人员
      AdminChecked: true,
      // 姓名
      userName: '',
      userGuid: '',
      // 房间号
      roomName: '',
      roomGuid: '',
      // 初始时间选择
      startTime: '',
      endTime: '',
      datetime: [],
      // 密码
      password: '',
      // 是否反锁开门
      backLock: false,
      // 被选中的数据
      optPersonnel: [],

      // 是否可以选择
      mondayChecked: false,
      tuesdayChecked: false,
      wednesdayChecked: false,
      thursdayChecked: false,
      fridayChecked: false,
      saturdayChecked: false,
      sundayChecked: false,
      // 星期时段多选
      valMonday: 0,
      valTuesday: 0,
      valWednesday: 0,
      valThursday: 0,
      valFriday: 0,
      valSaturday: 0,
      valSunday: 0,
      // 假日时段
      valHoliday: 0,
      // 添加人员弹框
      dialogVisible: false,
      addroomjonVisible: false,
      // 楼层弹窗
      addbuildroomVisible: false
    }
  },
  components: {
    AddRoomJon,
    AddBuildRoom
  },
  computed: {
    changeschoolid: {
      get() {
        // this.unitGuid = this.changeschoolid
        return this.$store.state.user.changeschoolid
      }
    }
  },
  created() {
    this.endTime = this.getimeto('yyyy-MM-dd HH:mm:ss')
    this.datetime = [
      this.lasttimemon('yyyy-MM-dd HH:mm:ss'),
      this.getimeto('yyyy-MM-dd HH:mm:ss')
    ]
    this.operatorGuid = sessionStorage.getItem('administrator')
    this.gestatistics()
  },
  filters: {
    handleEmpowerType(empower) {
      if (empower == 0) {
        return '未授权'
      }
      if (empower == 1) {
        return '指定房间'
      }
      if (empower == 2) {
        return '临时授权'
      }
      if (empower == 2) {
        return '导入授权'
      }
    }
  },
  mounted() {
    this.startTime = this.getimeto('yyyy-MM-dd HH:mm:ss')
    this.endTime = this.oneDay(1)
  },
  methods: {
    // 获取到房内人员授权信息
    gestatistics() {
      console.log(this.roomGuid)
      if (this.datetime == null) {
        this.searchInfo.startTime = ''
        this.searchInfo.endTime = ''
      } else {
        this.searchInfo.startTime = this.datetime[0]
        this.searchInfo.endTime = this.datetime[1]
      }
      this.searchInfo.unitGuid = this.unitGuid
      this.searchInfo.merchantGuid = this.consumptionpoint
      if (this.radio == 0) {
        this.searchInfo.timeType = 0
      } else if (this.radio == 1) {
        this.searchInfo.timeType = 1
      } else {
        this.searchInfo.timeType = 2
      }
      this.loading = true
      this.$http({
        url: this.$http.adornUrl(
          '/terminal/doorLock/room-empower-name-search-page'
        ),
        method: 'post',
        data: this.$http.adornData({
          messageContent: {
            pageNum: this.pageNum,
            pageSize: this.pageSize,
            searchInfo: { roomGuid: this.roomGuid }
          },
          messageType: 0
        })
      }).then(({ data }) => {
        this.loading = false
        if (data.messageCode == 200) {
          console.log(data)
          this.detailslist = data.messageContent.data
          this.recordCount = data.messageContent.recordCount
          this.currentPage = data.messageContent.pageNum
        } else {
          this.$message.error(data.errorMessage)
        }
      })
    },
    // 批量修改时间
    oneDay(day) {
      console.log(this.endTime)
      if (this.endTime != null && this.endTime != '') {
        let arr = []
        let timer = 0
        timer = this.endTime
        arr = timer.split('-')
        // 月份处理
        if (day == 30) {
          if (Number(arr[1]) % 2 == 1 && Number(arr[1]) <= 7) {
            day = 31
          } else if (Number(arr[1]) == 2) {
            //判断闰年还是平年
            if (
              (Number(arr[0]) % 4 == 0 && Number(arr[0]) % 100 != 0) ||
              Number(arr[0]) % 400 == 0
            ) {
              day = 29
            } else {
              day = 28
            }
          } else if (
            Number(arr[1]) % 2 == 0 &&
            Number(arr[1]) <= 12 &&
            Number(arr[1]) > 7
          ) {
            day = 31
          }
        }
        // 年份处理
        if (day == 365) {
          //判断闰年还是平年
          if (
            (Number(arr[0]) % 4 == 0 && Number(arr[0]) % 100 != 0) ||
            Number(arr[0]) % 400 == 0
          ) {
            day = 366
          }
        }
        console.log(this.endTime)
        console.log(Number(new Date(this.endTime).getTime()))
        console.log(
          Number(new Date(this.endTime).getTime()) + Number(1000 * 60 * 60 * 24)
        )
        timer = new Date(
          new Date(this.endTime).getTime() + 1000 * 60 * 60 * 24 * day
        )
        console.log(timer)
        let Y = timer.getFullYear() + '-'
        let M =
          (timer.getMonth() + 1 < 10
            ? '0' + (timer.getMonth() + 1)
            : timer.getMonth() + 1) + '-'
        let D = timer.getDate() < 10 ? '0' + timer.getDate() : timer.getDate()
        let h =
          timer.getHours() < 10 ? '0' + timer.getHours() : +timer.getHours()
        let m =
          timer.getMinutes() < 10
            ? '0' + timer.getMinutes()
            : +timer.getMinutes()
        let s =
          timer.getSeconds() < 10
            ? '0' + timer.getSeconds()
            : +timer.getSeconds()
        this.endTime = Y + M + D + ' ' + h + ':' + m + ':' + s
        return Y + M + D + ' ' + h + ':' + m + ':' + s
      } else {
        this.$message({
          message: '请选择结束时间',
          type: 'warning'
        })
      }
    },
    // 批量重置时间
    resetTime() {
      console.log(this.endTime)
      if (this.endTime != null && this.endTime != '') {
        this.endTime = this.getimeto('yyyy-MM-dd HH:mm:ss')
      } else {
        this.$message({
          message: '请选择结束时间',
          type: 'warning'
        })
      }
    },
    // 批量修改星期时段，时间
    handleValOne(val, key) {
      if (this.optPersonnel.length == 0) {
        return false
      }
      this.optPersonnel.map(item => {
        item[key] = val
      })
    },
    // 添加人员
    createPersonnel() {
      this.addroomjonVisible = true
      let isPersonnel = true
      this.$nextTick(() => {
        this.$refs.addroomjoin.addinit(this.roomGuid, isPersonnel)
      })
    },

    // 添加人员弹框按确定
    refreshDataList(val) {
      console.log(val)
      this.userName = val[0].userName
      this.userGuid = val[0].userGuid
      // 关闭弹窗
      this.addroomjonVisible = false

      this.gestatistics()
    },
    // 弹窗关闭
    handleClose() {
      this.dialogVisible = false
    },

    // 添加房间
    createRoom() {
      this.addbuildroomVisible = true
      this.$nextTick(() => {
        this.$refs.addbuildroomjoin.addinit(this.roomGuid)
      })
    },
    // 选择房间后返回数据
    refbuildDataList(val) {
      console.log(val)
      this.roomName = val[0] ? val[0].roomName : ''
      this.roomGuid = val[0] ? val[0].roomGuid : ''
      this.addbuildroomVisible = false
    },

    // 是否反锁关门
    backLockChange(val) {
      console.log(val)
      if (val) {
        this.backLock = 1
      } else {
        this.backLock = 0
      }
    },
    // 提交数据
    onSubmit() {
      console.log(this.backLock)
      let messageContent = {}
      if (this.AdminChecked) {
        if (this.userName == '') {
          this.$message({
            message: '用户必须选择',
            type: 'warning'
          })
          return false
        }
        // 被授权的人员Id
        messageContent.userGuid = this.userGuid
      }
      if (this.roomName == '') {
        this.$message({
          message: '房间必须选择',
          type: 'warning'
        })
        return false
      }
      if (this.startTime == '' || this.startTime == null) {
        this.$message({
          message: '开始时间必须选择',
          type: 'warning'
        })
        return false
      }
      if (this.endTime == '' || this.endTime == null) {
        this.$message({
          message: '结束时间必须选择',
          type: 'warning'
        })
        return false
      }
      // 假日时段
      if (this.valHoliday != 0) {
        messageContent.holidayTimeStageIndex = this.valHoliday
      }
      // 那个时段选中
      if (this.mondayChecked) {
        messageContent.mondayTimeStageIndex = this.valMonday
      }
      if (this.tuesdayChecked) {
        messageContent.tuesdayTimeStageIndex = this.valTuesday
      }
      if (this.wednesdayChecked) {
        messageContent.wednesdayTimeStageIndex = this.valWednesday
      }
      if (this.thursdayChecked) {
        messageContent.thursdayTimeStageIndex = this.valThursday
      }
      if (this.fridayChecked) {
        messageContent.fridayTimeStageIndex = this.valFriday
      }
      if (this.saturdayChecked) {
        messageContent.saturdayTimeStageIndex = this.valSaturday
      }
      if (this.sundayChecked) {
        messageContent.sundayTimeStageIndex = this.valSunday
      }
      // 操作用户id
      messageContent.operatorGuid = this.operatorGuid
      // 学校id
      messageContent.unitGuid = this.changeschoolid
      // 选择的房间id
      messageContent.roomGuid = this.roomGuid
      messageContent.startTime = this.startTime
      messageContent.endTime = this.endTime
      messageContent.password = this.password
      messageContent.backLock = this.backLock ? 1 : 0
      // 是否可以选择
      messageContent.mondayChecked = this.mondayChecked ? 1 : 0
      messageContent.tuesdayChecked = this.tuesdayChecked ? 1 : 0
      messageContent.wednesdayChecked = this.wednesdayChecked ? 1 : 0
      messageContent.thursdayChecked = this.thursdayChecked ? 1 : 0
      messageContent.fridayChecked = this.fridayChecked ? 1 : 0
      messageContent.saturdayChecked = this.saturdayChecked ? 1 : 0
      messageContent.sundayChecked = this.sundayChecked ? 1 : 0

      if (this.AdminChecked) {
        console.log(messageContent)
        this.$http({
          url: this.$http.adornUrl(
            '/terminal/doorLock/empower-name-room-temp-add'
          ),
          method: 'post',
          data: this.$http.adornData({
            messageContent: messageContent,
            messageType: 0
          })
        }).then(({ data }) => {
          this.loading = false
          if (data.messageCode == 200) {
            console.log(data)
            this.$message({
              message: '授权成功',
              type: 'success'
            })
            this.empty()
          } else {
            this.$message.error(data.errorMessage)
          }
        })
      } else {
        messageContent.cardNumber = this.ruleForm.cardNumber
        messageContent.userName = this.ruleForm.userName
        messageContent.phone = this.ruleForm.phone
        messageContent.idCard = this.ruleForm.idCard
        messageContent.position = this.ruleForm.position
        messageContent.sex = this.ruleForm.sex
        messageContent.birthday = this.ruleForm.birthday
        console.log(this.ruleForm)
        console.log(messageContent)
        this.$refs['ruleForm'].validate(valid => {
          if (valid) {
            this.$http({
              url: this.$http.adornUrl(
                '/terminal/doorLock/empower-name-not-system-temp-add'
              ),
              method: 'post',
              data: this.$http.adornData({
                messageContent: messageContent,
                messageType: 0
              })
            }).then(({ data }) => {
              this.loading = false
              if (data.messageCode == 200) {
                console.log(data)
                this.$message({
                  message: '授权成功',
                  type: 'success'
                })
                this.$refs['ruleForm'].resetFields()
                this.empty()
              } else {
                this.$message.error(data.errorMessage)
              }
            })
          } else {
            return false
          }
        })
      }
    },
    // 清空数据
    empty() {
      // 系统内人员
      this.AdminChecked = true
      // 姓名
      this.userName = ''
      this.userGuid = ''
      // 房间号
      this.roomName = ''
      this.roomGuid = ''
      // 初始时间选择
      this.startTime = this.getimeto('yyyy-MM-dd HH:mm:ss')
      this.endTime = this.getimeto('yyyy-MM-dd HH:mm:ss')
      this.endTime = this.oneDay(1)

      // 密码
      this.password = ''
      // 是否反锁开门
      this.backLock = false

      // 是否可以选择
      this.mondayChecked = false
      this.tuesdayChecked = false
      this.wednesdayChecked = false
      this.thursdayChecked = false
      this.fridayChecked = false
      this.saturdayChecked = false
      this.sundayChecked = false
      // 星期时段多选
      this.valMonday = 1
      this.valTuesday = 1
      this.valWednesday = 1
      this.valThursday = 1
      this.valFriday = 1
      this.valSaturday = 1
      this.valSunday = 1
      // 假日时段
      this.valHoliday = 0
    }
  }
}
</script>

<style lang="scss" scoped>
.page {
  display: flex;
  justify-content: center;
  align-items: center;
}
// 多选框的样式
.checked {
  margin: 0 31px 0 0;
}
.door {
  padding: 10px;
  .el-form-item {
    margin-bottom: 12px;
  }
}
.TimeWeek {
  padding: 20px 0 0;
}
.time {
  margin: 0 10px;
}
.el-dialog--center .el-dialog__body {
  padding: 0 50px;
}
// 隐藏纵向滚动条
</style>